package com.jdd.modules.mqtt.server.revice;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jdd.common.constant.FaceConstant;
import com.jdd.common.util.OssUtil;
import com.jdd.dao.entity.*;
import com.jdd.dao.service.*;
import com.jdd.modules.device.entity.TDevice;
import com.jdd.modules.device.service.TDeviceService;
import com.jdd.modules.dooropeningrecord.entity.DoorOpeningRecord;
import com.jdd.modules.dooropeningrecord.service.IDoorOpeningRecordService;
import com.jdd.modules.through.entity.Through;
import com.jdd.modules.through.service.IThroughService;
import com.jdd.modules.userstaff.entity.User;
import com.jdd.modules.userstaff.service.IUserService;
import com.jdd.modules.visitorLog.entity.VisitorLog;
import com.jdd.utils.SnowFlakeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @program: jdd-people-passage
 * @ClassName ReciveMqttQrResponseService
 * @description: 人脸识别结果topic消息处理类
 * @author: zsj
 * @create: 2022-03-24 09:56
 * @Version 1.0
 **/
@Service("mqttFaceResponseStrategy")
public class ReciveMqttFaceResponseServiceStrategy implements IReciveMqttBaseStrategy {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TDeviceFaceDiscernLogService faceDiscernLogService;
    @Resource
    private TDeviceIcDiscernLogService icDiscernLogService;
    @Resource
    private TDeviceIdcardDiscernLogService idcardDiscernLogService;
    @Autowired
    private TVisitPassMediumService visitPassMediumService;
    @Autowired
    private TUserPassMediumService userPassMediumService;
    @Resource
    private IUserService tUserService;
    @Resource
    private IDoorOpeningRecordService iDoorOpeningRecordService;
    @Autowired
    private OssUtil ossUtil;
    @Resource
    TDeviceService tDeviceService;
    @Resource
    IThroughService throughService;

    /**
     * 处理从mqtt接收到的人脸识别结果消息接口
     *
     * @param message 消息
     * @return void
     * @Description
     * @Author zsj
     * @Date 2022-03-24 9:53
     **/
    @Override
    public void handleMessage(String message) throws ParseException {
        logger.info("接收到mqtt人脸识别结果消息，消息：{}", message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        String type = jsonObject.getString("type");
        JSONObject body = jsonObject.getJSONObject("body");


        //公共参数
        String hat = body.getString("hat");
        String mask = body.getString("mask");
        String name = body.getString("name");
        String sequence = body.getString("sequence");
        String tep = body.getString("tep");

        //通道记录
        Through through = new Through();
        //人脸识别记录
        TDeviceFaceDiscernLog faceDiscernLog = null;
        //韦根卡记录
        TDeviceIcDiscernLog icDiscernLog = null;
        //身份证识别记录
        TDeviceIdcardDiscernLog idcardDiscernLog = null;
        if (type.equals(FaceConstant.PUSH_FACE_RESULT)) {
            faceDiscernLog = new TDeviceFaceDiscernLog();
            through.setThroughType(1);
            int e_imgsize = body.getInteger("e_imgsize");
            String e_imgurl = body.getString("e_imgurl");
            String img_data = body.getString("img_data");
            String isRealtimeData = body.getString("isRealtimeData");
            Boolean isurl = body.getBoolean("isurl");
            String idcard = body.getString("idcard");
            String matched = body.getString("matched");
            String name_base64 = body.getString("name_base64");
            String per_id = body.getString("per_id");
            String per_id_base64 = body.getString("per_id_base64");
            int role = body.getInteger("role");
            String sn = body.getString("sn");
            int usec = body.getInteger("usec");

            faceDiscernLog.setEImgsize(body.getInteger("e_imgsize"));
            faceDiscernLog.setEImgurl(body.getString("e_imgurl"));
            faceDiscernLog.setHat(body.getString("hat"));
            faceDiscernLog.setIdCard(body.getString("idcard"));
            if (StringUtils.isNotBlank(body.getString("img_data"))) {
                //上传阿里云
                String faceUrl = null;
                try {
                    faceUrl = ossUtil.uploadBaseString2OSS(body.getString("img_data"));
                } catch (IOException e) {
                    logger.error("上传人脸图片失败：" + e.getMessage());
                    e.printStackTrace();
                }
                faceDiscernLog.setImgData(faceUrl);
            }
            faceDiscernLog.setIsRealtimeData(isRealtimeData);
            faceDiscernLog.setIsUrl(isurl);
            faceDiscernLog.setMask(mask);
            faceDiscernLog.setMatched(matched);
            faceDiscernLog.setName(name);
            faceDiscernLog.setNameBase64(name_base64);
            faceDiscernLog.setPerId(per_id);
            faceDiscernLog.setPerIdBase64(per_id_base64);
            faceDiscernLog.setRole(role);
            faceDiscernLog.setSequence(sequence);
            faceDiscernLog.setSn(sn);
            faceDiscernLog.setTep(tep);
            faceDiscernLog.setUsec(usec);
            LambdaQueryWrapper<TDevice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TDevice::getDeviceSn,sn);
            TDevice one = tDeviceService.getOne(wrapper);
            if (one!=null){
                faceDiscernLog.setProjectId(one.getProjectId());
            }
            openLogAndThroughResultHandle(name, tep, through, isRealtimeData, per_id, sn, usec, 1, idcard, faceDiscernLog.getImgData());
            faceDiscernLogService.save(faceDiscernLog);

        }

        /**
         * 韦根卡识别结果
         * @author zxl
         * @date 2022/9/30 17:19
         */
        if (type.equals(FaceConstant.WGIN_READ)) {
            icDiscernLog = new TDeviceIcDiscernLog();
            through.setThroughType(2);
            //ic识别
            String sn = jsonObject.getString("sn");
            String age = body.getString("age");
            String code = body.getString("code");
            String error_msg = body.getString("error_msg");
            String imgdata = body.getString("imgdata");
            String imgexist = body.getString("imgexist");
            int imglen = body.getInteger("imglen");
            String imgpath = body.getString("imgpath");
            String match = body.getString("match");
            String matchRole = body.getString("matchRole");
            String per_id = body.getString("per_id");
            int tvsec = body.getInteger("tvsec");
            int wtype = body.getInteger("type");
            int wg_num = body.getInteger("wg_num");
            icDiscernLog.setHat(hat);
            icDiscernLog.setSn(sn);
            icDiscernLog.setError_msg(error_msg);
            if (StringUtils.isNotBlank(imgdata)) {
                //上传阿里云
                String faceUrl = null;
                try {
                    faceUrl = ossUtil.uploadBaseString2OSS(imgdata);
                } catch (IOException e) {
                    logger.error("上传人脸图片失败：" + e.getMessage());
                    e.printStackTrace();
                }
                icDiscernLog.setImgdata(faceUrl);
            }
            icDiscernLog.setTep(tep);
            icDiscernLog.setMask(mask);
            icDiscernLog.setImgexist(Integer.parseInt(imgexist));
            icDiscernLog.setTvsec(tvsec);
            icDiscernLog.setImglen(imglen);
            icDiscernLog.setWg_num(wg_num);
            icDiscernLog.setType(wtype);
            icDiscernLog.setUserId(per_id);
            icDiscernLog.setMatch(match);
            LambdaQueryWrapper<TDevice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TDevice::getDeviceSn,sn);
            TDevice one = tDeviceService.getOne(wrapper);
            if (one!=null){
                icDiscernLog.setProjectId(one.getProjectId());
            }
            openLogAndThroughResultHandle(name, tep, through, code, per_id, sn, tvsec, 2, String.valueOf(wg_num), faceDiscernLog.getImgData());
            icDiscernLogService.save(icDiscernLog);
        }

        /**
         * 身份证识别结果
         * @author zxl
         * @date 2022/9/30 17:18
         */
        if (type.equals(FaceConstant.IDCARD_READ)) {
            idcardDiscernLog = new TDeviceIdcardDiscernLog();
            through.setThroughType(3);
            //身份证识别推送
            String imgurl = jsonObject.getString("imgurl");
            String sn = jsonObject.getString("sn");
            String addr = body.getString("addr");
            String birthday = body.getString("birthday");
            String enddate = body.getString("enddate");
            String error_code = body.getString("error_code");
            String face_imgdata = body.getString("face_imgdata");
            String faceimglen = body.getString("faceimglen");
            String gender = body.getString("gender");
            String idcard = body.getString("idcard");
            Integer imglen = body.getInteger("imglen");
            String imgpath = body.getString("imgpath");
            String maker = body.getString("maker");
            String match = body.getString("match");
            String national = body.getString("national");
            String startdate = body.getString("startdate");
            int tvsec = body.getInteger("tvsec");
            openLogAndThroughResultHandle(name, tep, through, error_code, null, sn, tvsec, 3, idcard, faceDiscernLog.getImgData());
            LambdaQueryWrapper<TDevice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TDevice::getDeviceSn,sn);
            TDevice one = tDeviceService.getOne(wrapper);
            idcardDiscernLog.setBirthday(birthday);
            idcardDiscernLog.setFaceImgdata(imgurl);
            idcardDiscernLog.setFaceimglen(imglen);
           idcardDiscernLog.setMaker(maker);
           idcardDiscernLog.setIdCard(idcard);
           idcardDiscernLog.setName(name);
           idcardDiscernLog.setErrorCode(error_code);
           idcardDiscernLog.setHat(hat);
           idcardDiscernLog.setMask(mask);
           idcardDiscernLog.setSn(sn);
           idcardDiscernLog.setMatch(match);
           idcardDiscernLog.setTvsec(tvsec);
            if (one!=null){
                idcardDiscernLog.setProjectId(one.getProjectId());
            }
            idcardDiscernLogService.save(idcardDiscernLog);

            VisitorLog visitorLog = new VisitorLog();

        }

        /**
         * 封装通道记录
         * @author zxl
         * @date 2022/10/3 15:40
         */
        if (faceDiscernLog != null) {
            through.setDeviceSn(faceDiscernLog.getSn());
            through.setPeopleName(faceDiscernLog.getName());
            through.setPicture(faceDiscernLog.getImgData());
        }
        if (icDiscernLog != null) {
            through.setDeviceSn(icDiscernLog.getSn());
            through.setPeopleName(icDiscernLog.getName());
            through.setPicture(icDiscernLog.getImgdata());
        }
        if (idcardDiscernLog != null) {
            through.setDeviceSn(idcardDiscernLog.getSn());
            through.setPeopleName(idcardDiscernLog.getName());
            through.setPicture(idcardDiscernLog.getFaceImgdata());
        }
        if (through.getDeviceSn() != null) {
            QueryWrapper<TDevice> tDeviceQueryWrapper = new QueryWrapper<>();
            tDeviceQueryWrapper.eq("device_sn", through.getDeviceSn());
            TDevice one = tDeviceService.getOne(tDeviceQueryWrapper);
            through.setDeviceName(one.getDeviceAlias());
            through.setProjectName(one.getProjectName());
            through.setProjectId(one.getProjectId());

        }
        through.setId(SnowFlakeUtil.getId());
        through.setTemperature(tep);
        throughService.save(through);

    }

    private void openLogAndThroughResultHandle(String name, String tep, Through through, String isRealtimeData, String per_id, String sn, int usec, int openType, String cardNum, String img) throws ParseException {
        String res = isRealtimeData.substring(1);
        if (isRealtimeData.substring(1).equals("01")) {
            saveOpenDoor(name, tep, through, per_id, sn, usec, openType, cardNum, img);
            setResult(through, res);
        } else {
            setResult(through, res);
        }
    }

    private void setResult(Through through, String res) {
        if (res.equals("01")) {
            through.setResultType(1);
        } else if (res.equals("02")) {
            through.setResultType(2);
        } else if (res.equals("03")) {
            through.setResultType(3);
        } else if (res.equals("04")) {
            through.setResultType(4);
        } else if (res.equals("05")) {
            through.setResultType(5);
        } else if (res.equals("06")) {
            through.setResultType(6);
        } else if (res.equals("07")) {
            through.setResultType(7);
        } else if (res.equals("11")) {
            through.setResultType(11);
        } else if (res.equals("12")) {
            through.setResultType(12);
        }
    }

    private void saveOpenDoor(String name, String tep, Through through, String per_id, String sn, int usec, int openType, String cardNum, String img) throws ParseException {
        logger.info("白名单识别成功保存开门记录");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        through.setResultType(1);
        //封装识别成功开门记录
        QueryWrapper<TDevice> tDeviceQueryWrapper = new QueryWrapper<>();
        tDeviceQueryWrapper.eq("device_sn", sn);
        TDevice one = tDeviceService.getOne(tDeviceQueryWrapper);
        DoorOpeningRecord doorOpeningRecord = new DoorOpeningRecord();
        doorOpeningRecord.setId(SnowFlakeUtil.getId());
        doorOpeningRecord.setProjectName(one.getProjectName());
        doorOpeningRecord.setBodySurfaceTemperature(tep);
        doorOpeningRecord.setDeviceId(sn);
        doorOpeningRecord.setDeviceName(one.getDeviceAlias());
        doorOpeningRecord.setDoorOpeningType(openType);
        doorOpeningRecord.setName(name);

        doorOpeningRecord.setProjectId(one.getProjectId());
        doorOpeningRecord.setImg(img);
        doorOpeningRecord.setOpeningTime(simpleDateFormat.parse(simpleDateFormat.format(Long.valueOf(String.valueOf(usec)) * 1000L)));
        doorOpeningRecord.setAreaId(one.getAreaId());

        if (per_id != null) {

            User byId = tUserService.getById(per_id);
            if (byId!=null){
                doorOpeningRecord.setPhoneNumber(byId.getMobile());
                doorOpeningRecord.setCardNumber(byId.getIdCard());
            }else {
                logger.warn("找不到用户的信息，或用户非系统添加");
            }
        }
        doorOpeningRecord.setCardNumber(cardNum);
        iDoorOpeningRecordService.save(doorOpeningRecord);
    }
}